package com.jnu.bookmanagermainactivity;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.MenuItemCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;


import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.bookmanagermainactivity.data.BookItem;
import com.jnu.bookmanagermainactivity.data.DataSaver;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    public static final int MENU_ID_ADD = 1;
    public static final int MENU_ID_UPDATE = 2;
    public static final int MENU_ID_DELETE = 3;
    private ArrayList<BookItem> bookItems;
    private MainRecycleViewAdapter mainRecycleViewAdapter;

    //addDataLauncher在返回的时候会调用“result ->"函数
    private ActivityResultLauncher<Intent> addDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            , result -> {
                //如果返回结果不是null的话
                if (null != result) {
                    Intent intent = result.getData();
                    //获得bundle数据
                    if (result.getResultCode() == InputBookItemActivity.RESULT_CODE_SUCCESS) {
                        Bundle bundle = intent.getExtras();
                        String title = bundle.getString("title");
                        double price = bundle.getDouble("price");
                        int position = bundle.getInt("position");
                        bookItems.add(position, new BookItem(title, price, R.drawable.book_no_name));//传回值
                        new DataSaver().Save(this, bookItems);
                        mainRecycleViewAdapter.notifyItemInserted(position); //通知适配器
                    }
                }
            });
    private ActivityResultLauncher<Intent> updateDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            , result -> {
                //如果返回结果不是null的话
                if (null != result) {
                    Intent intent = result.getData();
                    //获得bundle数据
                    if (result.getResultCode() == InputBookItemActivity.RESULT_CODE_SUCCESS) {
                        Bundle bundle = intent.getExtras();
                        String title = bundle.getString("title");
                        double price = bundle.getDouble("price");
                        int position = bundle.getInt("position");
                        bookItems.get(position).setTitle(title);
                        bookItems.get(position).setPrice(price);
                        new DataSaver().Save(this, bookItems);
                        mainRecycleViewAdapter.notifyItemChanged(position); //通知适配器
                    }
                }
            });

    //registerForActivityResult要在onCreate前面调用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recycleViewMain = findViewById(R.id.recycle_view_books);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleViewMain.setLayoutManager(linearLayoutManager);

        DataSaver dataSaver = new DataSaver();
        bookItems = dataSaver.Load(this);

        if (bookItems.size() == 0) {
            bookItems.add(new BookItem(getString(R.string.book_1_name), Math.random() * 10, R.drawable.book_1));
            bookItems.add(new BookItem(getString(R.string.book_2_name), Math.random() * 10, R.drawable.book_2));
            bookItems.add(new BookItem(getString(R.string.book_no_name_name), Math.random() * 10, R.drawable.book_no_name));
        }
        //bookItems = new ArrayList<>();
        /*for(int i=1;i<20;++i)
        {
            if(i%3==1) bookItems.add(new BookItem(getString(R.string.book_1_name),Math.random()*10,R.drawable.book_1));
            if(i%3==2) bookItems.add(new BookItem(getString(R.string.book_2_name),Math.random()*10,R.drawable.book_2));
            if(i%3==0) bookItems.add(new BookItem(getString(R.string.book_no_name_name),Math.random()*10,R.drawable.book_no_name));
        }*/

        mainRecycleViewAdapter = new MainRecycleViewAdapter(bookItems);
        recycleViewMain.setAdapter(mainRecycleViewAdapter);

        //add悬浮按钮
        FloatingActionButton add = (FloatingActionButton) findViewById(R.id.float_add_button);
        //设置监听
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, InputBookItemActivity.class);
                addDataLauncher.launch(intent);//启动一个窗口，在返回的时候可以调用“result ->"函数，返回一个结果
            }
        });

        //设置主界面搜索按钮的点击事件
        ImageButton search = (ImageButton) findViewById(R.id.search_button);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SearchBookItemActivity.class);
                addDataLauncher.launch(intent);//启动一个窗口，在返回的时候可以调用“result ->"函数，返回一个结果
            }
        });


    }


    @Override
    //长按菜单
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case MENU_ID_ADD:
                Intent intent = new Intent(this, InputBookItemActivity.class);
                intent.putExtra("position", item.getOrder());//把位置传到子窗口去
                addDataLauncher.launch(intent);//启动一个窗口，在返回的时候可以调用“result ->"函数，返回一个结果
                break;
            case MENU_ID_UPDATE:
                Intent intentUpdate = new Intent(this, InputBookItemActivity.class);
                intentUpdate.putExtra("position", item.getOrder());//把位置传到子窗口去
                intentUpdate.putExtra("title", bookItems.get(item.getOrder()).getTitle());
                intentUpdate.putExtra("price", bookItems.get(item.getOrder()).getPrice());
                updateDataLauncher.launch(intentUpdate);
                break;
            case MENU_ID_DELETE:
                //点击delete时弹出对话框，确定是否删除，两个响应函数
                AlertDialog alertDialog;
                alertDialog = new AlertDialog.Builder(this)
                        .setTitle(R.string.confirmation)
                        .setMessage(R.string.sure_to_delete)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                bookItems.remove(item.getOrder());//删除选中项
                                new DataSaver().Save(MainActivity.this, bookItems);
                                mainRecycleViewAdapter.notifyItemRemoved(item.getOrder());//通知适配器
                            }
                        }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).create();
                alertDialog.show();
                break;
        }
        return super.onContextItemSelected(item);


    }

    public class MainRecycleViewAdapter extends RecyclerView.Adapter<MainRecycleViewAdapter.ViewHolder> {

        private ArrayList<BookItem> localDataSet;

        /**
         * Provide a reference to the type of views that you are using
         * (custom ViewHolder).
         */
        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            private final TextView textViewTitle;

            public TextView getTextViewPrice() {
                return textViewPrice;
            }

            private final TextView textViewPrice;
            private final ImageView imageViewImage;

            public ViewHolder(View view) {
                super(view);
                // Define click listener for the ViewHolder's View

                imageViewImage = view.findViewById(R.id.image_view_book_cover);
                textViewTitle = view.findViewById(R.id.text_view_book_title);
                textViewPrice = view.findViewById(R.id.text_view_book_price);

                view.setOnCreateContextMenuListener(this);
            }

            public TextView getTextViewTitle() {
                return textViewTitle;
            }

            public ImageView getImageViewImage() {
                return imageViewImage;
            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                contextMenu.add(0, MENU_ID_ADD, getAdapterPosition(), "Add " + getAdapterPosition());
                contextMenu.add(0, MENU_ID_UPDATE, getAdapterPosition(), "Update " + getAdapterPosition());
                contextMenu.add(0, MENU_ID_DELETE, getAdapterPosition(), "Delete " + getAdapterPosition());
            }
        }

        /**
         * Initialize the dataset of the Adapter.
         *
         * @param dataSet String[] containing the data to populate views to be used
         *                by RecyclerView.
         */
        public MainRecycleViewAdapter(ArrayList<BookItem> dataSet) {
            localDataSet = dataSet;
        }//传进去同一个对象

        // Create new views (invoked by the layout manager)
        @Override
        @NonNull
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            // Create a new view, which defines the UI of the list item
            View view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.item_main, viewGroup, false);

            return new ViewHolder(view);
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {

            // Get element from your dataset at this position and replace the
            // contents of the view with that element
            viewHolder.getTextViewTitle().setText(localDataSet.get(position).getTitle());
            viewHolder.getTextViewPrice().setText(localDataSet.get(position).getPrice().toString());
            viewHolder.getImageViewImage().setImageResource(localDataSet.get(position).getResourceId());
            //if(position%3==0) viewHolder.getImageViewImage().setImageResource(localDataSet.get(position).getResourceId());
            //if(position%3==1) viewHolder.getImageViewImage().setImageResource(R.drawable.book_2);
            //if(position%3==2) viewHolder.getImageViewImage().setImageResource(R.drawable.book_no_name);
        }

        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return localDataSet.size();
        }



    }





}
